<template>
  <div class="invite-records">
    <h2>子页签2—邀请记录</h2>
    
    <!-- 搜索区域 -->
    <div class="search-area">
      <!-- 添加按钮 -->
      <div class="action-buttons">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="showAddDialog">添加邀请关系</el-button>
      </div>
      
      <div class="search-form">
        <el-form :inline="true" :model="searchForm" size="small">
          <el-form-item label="被邀请人">
            <el-input v-model="searchForm.uid" placeholder="请输入被邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="邀请人(上1级)">
            <el-input v-model="searchForm.parent1" placeholder="请输入邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="邀请人(上2级)">
            <el-input v-model="searchForm.Parent2" placeholder="请输入邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="邀请人(上3级)">
            <el-input v-model="searchForm.Parent3" placeholder="请输入邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="邀请人(上4级)">
            <el-input v-model="searchForm.Parent4" placeholder="请输入邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="邀请人(上5级)">
            <el-input v-model="searchForm.Parent5" placeholder="请输入邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="邀请人(上6级)">
            <el-input v-model="searchForm.Parent6" placeholder="请输入邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="邀请人(上7级)">
            <el-input v-model="searchForm.Parent7" placeholder="请输入邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="邀请人(上8级)">
            <el-input v-model="searchForm.Parent8" placeholder="请输入邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="邀请人(上9级)">
            <el-input v-model="searchForm.Parent9" placeholder="请输入邀请人ID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="渠道">
            <el-select v-model="searchForm.channel" placeholder="请选择渠道" style="width: 150px;" clearable>
              <el-option
                v-for="item in channelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="邀请时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格内容 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>邀请记录</span>
          <el-button 
            type="success" 
            size="small" 
            icon="el-icon-download"
            style="float: right;"
            @click="exportData"
            :loading="exportLoading">
            导出CSV
          </el-button>
        </div>
        
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          class="invite-table"
          v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="uid" label="被邀请人" width="120"></el-table-column>
          <el-table-column prop="parent1" label="邀请人（上1级）" width="120"></el-table-column>
          <el-table-column prop="Parent2" label="邀请人（上2级）" width="120"></el-table-column>
          <el-table-column prop="Parent3" label="邀请人（上3级）" width="120"></el-table-column>
          <el-table-column prop="Parent4" label="邀请人（上4级）" width="120"></el-table-column>
          <el-table-column prop="Parent5" label="邀请人（上5级）" width="120"></el-table-column>
          <el-table-column prop="channel" label="渠道" width="80"></el-table-column>
          <el-table-column prop="createTime" label="邀请时间" width="180"></el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 添加邀请关系对话框 -->
    <el-dialog
      title="添加邀请关系"
      :visible.sync="addDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addForm"
        label-width="100px"
      >
        <el-form-item label="被邀请人" prop="uid">
          <el-input
            v-model="addForm.uid"
            placeholder="请输入被邀请人ID"
            type="number"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="邀请人" prop="parent">
          <el-input
            v-model="addForm.parent"
            placeholder="请输入邀请人ID"
            type="number"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="confirmAdd" :loading="addLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { agentList, agentAdd } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'InviteRecords',
  mixins: [channelMixin],
  data() {
    return {
      loading: false,
      searchForm: {
        uid: '',
        parent1: '',
        Parent2: '',
        Parent3: '',
        Parent4: '',
        Parent5: '',
        Parent6: '',
        Parent7: '',
        Parent8: '',
        Parent9: '',
        channel: null,
        dateRange: []
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 添加邀请关系相关数据
      addDialogVisible: false,
      addLoading: false,
      addForm: {
        uid: '',
        parent: ''
      },
      addRules: {
        uid: [
          { required: true, message: '请输入被邀请人ID', trigger: 'blur' },
          { pattern: /^\d+$/, message: '请输入有效的数字ID', trigger: 'blur' }
        ],
        parent: [
          { required: true, message: '请输入邀请人ID', trigger: 'blur' },
          { pattern: /^\d+$/, message: '请输入有效的数字ID', trigger: 'blur' }
        ]
      },
      exportLoading: false
    }
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    async fetchData() {
      this.loading = true
      try {
        const params = {
          uid: this.searchForm.id ? parseInt(this.searchForm.id) : 0, // 被邀请人
          parent1: 0, // 邀请人 0:任意
          Parent2: 0, // 邀请人 0:任意
          Parent3: 0, // 邀请人 0:任意
          Parent4: 0, // 邀请人 0:任意
          Parent5: 0, // 邀请人 0:任意
          Parent6: 0, // 邀请人 0:任意
          Parent7: 0, // 邀请人 0:任意
          Parent8: 0, // 邀请人 0:任意
          Parent9: 0, // 邀请人 0:任意
          channel: this.formatChannelParam(this.searchForm.channel),
          begin_time: this.searchForm.dateRange && this.searchForm.dateRange[0] ? 
            this.searchForm.dateRange[0] + ' 00:00:00' : '',
          end_time: this.searchForm.dateRange && this.searchForm.dateRange[1] ? 
            this.searchForm.dateRange[1] + ' 23:59:59' : '',
          page: this.currentPage,
          page_size: this.pageSize
        }
        
        console.log('===== InviteRecords Debug Info =====')
        console.log('发送参数:', params)
        
        const response = await agentList(params)
        console.log('接口返回完整数据:', response)
        
        if (response && response.code === 0) {
          console.log('接口成功，response.data:', response.data)
          console.log('response.data的类型:', typeof response.data)
          console.log('response.data的结构:', Object.keys(response.data || {}))
          
          // 尝试多种可能的数据结构
          let records = []
          if (response.data && response.data.agents && Array.isArray(response.data.agents)) {
            records = response.data.agents
            console.log('使用 response.data.agents')
          } else if (response.data && response.data.records && Array.isArray(response.data.records)) {
            records = response.data.records
            console.log('使用 response.data.records')
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            records = response.data.list
            console.log('使用 response.data.list')
          } else if (Array.isArray(response.data)) {
            records = response.data
            console.log('使用 response.data 直接数组')
          } else if (response.data && response.data.data && Array.isArray(response.data.data)) {
            records = response.data.data
            console.log('使用 response.data.data')
          } else {
            console.log('未找到数组数据，尝试遍历所有属性:')
            if (response.data && typeof response.data === 'object') {
              for (let key in response.data) {
                console.log(`response.data.${key}:`, response.data[key], 'isArray:', Array.isArray(response.data[key]))
                if (Array.isArray(response.data[key])) {
                  records = response.data[key]
                  console.log(`找到数组数据在 response.data.${key}`)
                  break
                }
              }
            }
          }
          
          console.log('解析后的records:', records)
          console.log('records长度:', records.length)
          console.log('records第一条数据:', records[0])
          
          // 直接使用API返回的数据
          this.tableData = records
          
          // 处理总数
          if (response.data && response.data.total_page) {
            this.total = response.data.total_page * this.pageSize
          } else if (response.data && response.data.total) {
            this.total = response.data.total
          } else if (response.total_page) {
            this.total = response.total_page * this.pageSize
          } else if (response.total) {
            this.total = response.total
          } else {
            this.total = records.length
          }
          
          console.log('设置tableData长度:', this.tableData.length)
          console.log('当前tableData:', this.tableData)
          console.log('设置total:', this.total)
          
          // 强制视图更新
          this.$nextTick(() => {
            this.$forceUpdate()
          })
          
        } else {
          console.error('接口返回错误:', response)
          this.$message.error(response.msg || response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取邀请记录数据失败:', error)
        this.$message.error('获取数据失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm = {
        id: '',
        dateRange: [],
        channel: null
      }
      this.currentPage = 1
      this.fetchData()
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          uid: this.searchForm.uid ? parseInt(this.searchForm.uid) : 0,
          parent1: this.searchForm.parent1 ? parseInt(this.searchForm.parent1) : 0,
          channel: this.formatChannelParam(this.searchForm.channel),
          begin_time: this.searchForm.dateRange && this.searchForm.dateRange[0] ? this.searchForm.dateRange[0] : '',
          end_time: this.searchForm.dateRange && this.searchForm.dateRange[1] ? this.searchForm.dateRange[1] : '',
          page: 1,
          page_size: 10000
        }
        
        const response = await agentList(params)
        const allData = response.data.agents || []
        
        const columns = [
          { prop: 'Id', label: 'ID' },
          { prop: 'uid', label: '被邀请人' },
          { prop: 'parent1', label: '邀请人' },
          { prop: 'channel', label: '渠道' },
          { prop: 'createTime', label: '邀请时间' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `邀请记录_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    },
    // 显示添加对话框
    showAddDialog() {
      this.addDialogVisible = true
      this.resetAddForm()
    },
    // 取消添加
    cancelAdd() {
      this.addDialogVisible = false
      this.resetAddForm()
    },
    // 重置添加表单
    resetAddForm() {
      this.addForm = {
        uid: '',
        parent: ''
      }
      if (this.$refs.addForm) {
        this.$refs.addForm.clearValidate()
      }
    },
    // 确认添加
    async confirmAdd() {
      try {
        // 表单验证
        await this.$refs.addForm.validate()
        
        this.addLoading = true
        
        const params = {
          uid: parseInt(this.addForm.uid), // 被邀请人
          parent: parseInt(this.addForm.parent) // 邀请人
        }
        
        console.log('===== AgentAdd Debug Info =====')
        console.log('发送参数:', params)
        
        const response = await agentAdd(params)
        console.log('接口返回数据:', response)
        
        if (response && response.code === 0) {
          this.$message.success('邀请关系添加成功')
          this.addDialogVisible = false
          this.resetAddForm()
          // 刷新列表数据
          this.fetchData()
        } else {
          console.error('添加邀请关系失败:', response)
          this.$message.error(response.msg || response.message || '添加失败')
        }
      } catch (error) {
        if (error.fields) {
          // 表单验证失败
          console.log('表单验证失败:', error)
          return
        }
        console.error('添加邀请关系失败:', error)
        this.$message.error('添加失败: ' + error.message)
      } finally {
        this.addLoading = false
      }
    }
  },
  mounted() {
    this.fetchData()
  }
}
</script>

<style scoped>
.invite-records {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-start;
}

.search-options {
  margin-bottom: 10px;
}

.search-label {
  font-size: 14px;
  margin-right: 20px;
  color: #f56c6c;
}

.invite-table {
  border: 1px solid #e6e6e6;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.export-tip {
  font-size: 14px;
  color: #606266;
}
</style> 